1029E - Tree with Small Distances - CodeForces Solution


dp graphs greedy *2100

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0);cin.tie(0)
#define endl "\n"  
#define fo(i,a,n) for (int i=a;i<=n;i++)
#define ro(i,a,n) for (int i=n;i>=a;i--)
#define yes cout<<"YES"<<endl
#define no  cout<<"NO"<<endl
#define fi first
#define se second
#define pb push_back 
#define int long long
//#pragma GCC optimize(2)
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;
const int N=2e5+10,mod=1000000007;
int n,m;
int a[N],d[N],st[N],f[N];
int gcd(int a, int b) {  if (b == 0) {return a;}  return gcd(b, a % b);}
// gcd(a,b,c,d)=gcd(a,gcd(b,c,d))=gcd(a,gcd(b-a,c-a,d-a))
int lcm(int a, int b) {return a * b / gcd(a, b);}
int qmi(int a, int b){int res=1%mod;a%=mod;while(b){if(b&1)res=res*a%mod;a=a*a%mod;b>>=1;}return res;} 
vector<int> e[N];
void dfs(int u,int fa){
	if(u!=1)d[u]=d[fa]+1;
	for(auto v:e[u])
	if(v!=fa)f[v]=u,dfs(v,u);
	return ;
}
signed main()
{
	IOS;cin>>n;
	fo(i,1,n-1){
		int u,v;cin>>u>>v;
		e[u].pb(v),e[v].pb(u);
	}
	dfs(1,0);
	priority_queue<PII > s; int ans=0;
	fo(i,1,n)if(d[i]>2)s.push({d[i],i});
	while(s.size()){
		auto pos=s.top();s.pop();
		int idx=pos.se;
		if(st[idx])continue ;
		st[idx]=1;ans++;
		for(auto v:e[idx])st[v]=1;
		for(auto v:e[f[idx]])st[v]=1;
	}
	cout<<ans<<endl;
	return 0;
}


Comments

Submit
0 Comments
More Questions

1581A - CQXYM Count Permutations
337A - Puzzles
495A - Digital Counter
796A - Buying A House
67A - Partial Teacher
116A - Tram
1472B - Fair Division
1281C - Cut and Paste
141A - Amusing Joke
112A - Petya and Strings
677A - Vanya and Fence
1621A - Stable Arrangement of Rooks
472A - Design Tutorial Learn from Math
1368A - C+=
450A - Jzzhu and Children
546A - Soldier and Bananas
32B - Borze
1651B - Prove Him Wrong
381A - Sereja and Dima
41A - Translation
1559A - Mocha and Math
832A - Sasha and Sticks
292B - Network Topology
1339A - Filling Diamonds
910A - The Way to Home
617A - Elephant
48A - Rock-paper-scissors
294A - Shaass and Oskols
1213A - Chips Moving
490A - Team Olympiad